package ast.stmt;

import icg.EQLabel;
import icg.EQLiteral;
import icg.Quadruple;
import ts.SymbolTable;
import ast.Node;
import ast.exp.Expression;
import ast.type.Type;

public class ReturnStmt extends Statement {
	private Expression exp;
	private Type typeExp;;
	public ReturnStmt(Expression exp) {
		this.exp = exp;
	}

	@Override
	public String toString() {
		return "<ReturnStmt>\n" + exp + "\n</ReturnStmt>";
	}

	@Override
	public void typeCheck(Type type) {
		if (type != Type.VOID) {
			typeExp = exp.typeCheck();
			if (typeExp != type) {
				System.out.println("invalid type in return");
				SymbolTable.errors++;
			}
		}
	}

	@Override
	public Boolean isReturned() {
		return true;
	}

	@Override
	public void genCode() {
		if (typeExp == Type.BOOLEAN) {
			EQLabel l1 = new EQLabel();
			EQLabel l2 = new EQLabel();
			exp.trueL = l1;
			exp.falseL = EQLabel.FALL;
			exp.genCode();
			Node.icg.gen(Quadruple.retorno(new EQLiteral("0")));
			Node.icg.gen(Quadruple.jump(l2));
			EQLabel.useLabel(l1);
			Node.icg.gen(Quadruple.retorno(new EQLiteral("1")));
			EQLabel.useLabel(l2);
		} else {//Nao booleano
			exp.genCode();
			Node.icg.gen(Quadruple.retorno(exp.addr));
		}
	}
}
